// 引入控制器类
const { Controller } = require('egg');

// 定义自己的控制器类
class StudentController extends Controller {
    async getStudent() {
        // 与数据库操作在service里面
        let list = await this.ctx.service.student.getStudentList()
        if (list) {
            this.ctx.body = {
                code: 20000,
                message: "获取数据成功",
                data: list
            }
        } else {
            this.ctx.body = {
                code: 50000,
                message: "服务器异常，请与管理员联系"
            }
        }
        
    };

    async getStudentById() {
        let id = this.ctx.params.id
        // 查询数据(根据条件)
        const data = await this.app.model.Student.findAll({ where: { id }}) 
        this.ctx.body = {
            code: 20000,
            message: "获取数据成功",
            data
        }
    };

    async addStudent() {
        const data = this.ctx.request.body
        // 添加数据
        await this.app.model.Student.create({
            name: data.name,
            age: data.age
        })
        this.ctx.body = {
            code: 20000,
            message: "添加数据成功",
        }
    };

    async deleteStudent() {
        let id = this.ctx.params.id
        // 删除数据
        await this.app.model.Student.destroy({ 
            where: { id }
        })
        this.ctx.body = {
            code: 20000,
            message: "删除数据成功",
        }
    };

    async updateStudent() {
        let id = this.ctx.params.id
        const data = this.ctx.request.body
        // 修改数据
        await this.app.model.Student.update(
            { name: data.name, age: data.age },
            { where: { id }}
        )
        this.ctx.body = {
            code: 20000,
            message: "修改数据成功",
        }
    };
}

module.exports = StudentController;
